package com.example.workflow.config;


import com.example.workflow.mapper.UserInfoMapper;
import com.example.workflow.pojo.LoginUser;
import com.example.workflow.pojo.UserInfo;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailsService implements UserDetailsService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        /*
          1/通过userName 获取到userInfo信息
          2/通过User（UserDetails）返回details。
         */
        //通过userName获取用户信息
        UserInfo userInfo = userInfoMapper.getUserInfoByUserName(userName);
        // TODO 如果没有获取到用户信息，后续处理？？？
        if(userInfo == null) {
            throw new UsernameNotFoundException("NOT_FOUND");
        }
        //定义权限列表.
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 用户可以访问的资源名称（或者说用户所拥有的权限） 注意：必须"ROLE_"开头
        authorities.add(new SimpleGrantedAuthority("ROLE_"+ userInfo.getRole()));
        List<String> permissions = new ArrayList<>();
        permissions.add("ROLE_"+userInfo.getRole());
        return new LoginUser(userInfo,permissions,authorities);
    }
}
